package controllers

import dao._
import models.Tables._
import org.joda.time.DateTime
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import tool.{FormTool, Tool}
import utils.Utils

import javax.inject.Inject
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import implicits.Implicits._

/**
 * Created by Administrator on 2019/8/7
 */
class SampleIdController @Inject()(cc: ControllerComponents)(
  implicit val accountDao: AccountDao,
  implicit val wechatMemberDao: WechatMemberDao,
  implicit val sampleIdDao: SampleIdDao
) extends
  AbstractController(cc) {

  def getNewIds = Action.async { implicit request =>
    val data = FormTool.produceQrcodeForm.bindFromRequest().get
    sampleIdDao.selectAll.map { x =>
      val dbIds = x.map(_.id).toList

      def loop(dbIds: List[String], newIds: List[String]): List[String] = {
        if (newIds.isEmpty || (newIds ::: dbIds).nonUniq) {
          val curNewIds = (1 to data.num).map { curI =>
            Tool.productValidCode
          }.toList
          loop(dbIds, curNewIds)
        } else newIds
      }

      val newIds = loop(dbIds, List.empty)
      Ok(Json.toJson(newIds))
    }
  }

  def add2Db = Action.async { implicit request =>
    val data = FormTool.idStrsForm.bindFromRequest().get
    val account=FormTool.accountForm.bindFromRequest().get.account
    val rows = data.ids.map { id =>
      SampleIdRow(id = id, memberAccount = account, downloadTime = new DateTime())
    }
    sampleIdDao.updates(rows).map { x =>
      Ok(Json.toJson("success"))
    }
  }


}
